package com.fiberhome.nas.feature.photo.view

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.fiberhome.nas.core.designsystem.theme.AppTheme
import com.fiberhome.nas.core.model.preview.previewPhotos
import com.fiberhome.nas.core.ui.R

// 相册数据类
data class Album(
    val id: String,
    val name: String,
    val photoCount: Int
)

// 照片数据类
data class PhotoItem(
    val id: String,
    val date: String,
    val imageResId: Int,
    val isBackedUp: Boolean = false // 备份状态
)

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AiPhotoAlbumScreen(
    onBackClick: () -> Unit = {},
    modifier: Modifier = Modifier
) {
    // 相册数据
    val albums = remember {
        listOf(
            Album("all", "所有照片", 15),
            Album("camera", "相机", 10),
            Album("screenshots", "截图", 5),
            Album("album1", "相册1", 8),
            Album("album2", "相册2", 12)
        )
    }

    // 上传目标数据
    val uploadTargets = remember {
        listOf("照片", "云端", "本地存储")
    }

    // 状态管理
    var selectedAlbum by remember { mutableStateOf(albums[3]) } // 默认选中"相册1"
    var isAlbumDropdownExpanded by remember { mutableStateOf(false) }
    var showUnbackedUpOnly by remember { mutableStateOf(false) } // 仅显示未备份照片
    val selectedPhotos = remember { mutableSetOf<String>() }
    val dateGroupSelection = remember { mutableMapOf<String, Boolean>() } // 日期组选择状态
    var selectedUploadTarget by remember { mutableStateOf(uploadTargets[0]) } // 默认上传目标
    var isUploadTargetDropdownExpanded by remember { mutableStateOf(false) }
    val gridState = rememberLazyGridState()

    // 模拟照片数据
    val photos = remember {
        listOf(
            PhotoItem("1", "2025-3-26", R.drawable.ic_alipay, isBackedUp = false),
            PhotoItem("2", "2025-3-26", R.drawable.ic_alipay, isBackedUp = true),
            PhotoItem("3", "2025-3-26", R.drawable.ic_alipay, isBackedUp = false),
            PhotoItem("4", "2025-3-26", R.drawable.ic_alipay, isBackedUp = false),
            PhotoItem("5", "2025-3-20", R.drawable.ic_alipay, isBackedUp = true),
            PhotoItem("6", "2025-3-20", R.drawable.ic_alipay, isBackedUp = false)
        )
    }

    // 根据筛选条件过滤照片
    val filteredPhotos = if (showUnbackedUpOnly) {
        previewPhotos.filter { !it.isBackedUp }
    } else {
        previewPhotos
    }

    // 按日期分组
    val photosByDate = filteredPhotos.groupBy { it.date }

    // 全选/取消全选功能
    val toggleSelectAll = {
        if (selectedPhotos.size == filteredPhotos.size) {
            selectedPhotos.clear()
            dateGroupSelection.keys.forEach { dateGroupSelection[it] = false }
        } else {
            filteredPhotos.forEach { selectedPhotos.add(it.id) }
            photosByDate.keys.forEach { dateGroupSelection[it] = true }
        }
    }

    // 日期组选择功能
    val toggleDateGroupSelection = { date: String ->
        val photosInGroup = photosByDate[date]
        val isGroupSelected = dateGroupSelection[date] ?: false

        if (isGroupSelected) {
            photosInGroup?.forEach { selectedPhotos.remove(it.id) }
            dateGroupSelection[date] = false
        } else {
            photosInGroup?.forEach { selectedPhotos.add(it.id) }
            dateGroupSelection[date] = true
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Box {
                        TextButton(
                            onClick = { isAlbumDropdownExpanded = true }
                        ) {
                            Text(
                                text = selectedAlbum.name,
                                fontWeight = FontWeight.Bold,
                                fontSize = 18.sp
                            )
                            Icon(
                                imageVector = Icons.Default.MoreVert,
                                contentDescription = "选择相册"
                            )
                        }
                        DropdownMenu(
                            expanded = isAlbumDropdownExpanded,
                            onDismissRequest = { isAlbumDropdownExpanded = false }
                        ) {
                            albums.forEach { album ->
                                DropdownMenuItem(
                                    text = { Text("${album.name} (${album.photoCount})") },
                                    onClick = {
                                        selectedAlbum = album
                                        isAlbumDropdownExpanded = false
                                        selectedPhotos.clear()
                                        dateGroupSelection.clear()
                                    }
                                )
                            }
                        }
                    }
                },
                navigationIcon = {
                    TextButton(onClick = {
                        selectedPhotos.clear()
                        dateGroupSelection.clear()
                    }) {
                        Text("取消")
                    }
                },
                actions = {
                    TextButton(onClick = toggleSelectAll) {
                        Text("取消全选")
                    }
                }
            )
        },
        bottomBar = {
            // 底部操作栏
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp, 16.dp, 16.dp, 56.dp)
                    .background(Color.Gray),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 上传至下拉菜单
                Box {
                    TextButton(onClick = { isUploadTargetDropdownExpanded = true }) {
                        Text("上传至: $selectedUploadTarget")
                    }
                    DropdownMenu(
                        expanded = isUploadTargetDropdownExpanded,
                        onDismissRequest = { isUploadTargetDropdownExpanded = false }
                    ) {
                        uploadTargets.forEach { target ->
                            DropdownMenuItem(
                                text = { Text(target) },
                                onClick = {
                                    selectedUploadTarget = target
                                    isUploadTargetDropdownExpanded = false
                                }
                            )
                        }
                    }
                }

                // 上传按钮
                Button(
                    onClick = { /* 上传操作 */ },
                    colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF007AFF))
                ) {
                    Text("上传(${selectedPhotos.size})")
                }
            }
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
        ) {
            // 仅显示未备份照片开关
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp, vertical = 8.dp),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Text("仅显示未备份照片")
                Switch(
                    checked = showUnbackedUpOnly,
                    onCheckedChange = {
                        showUnbackedUpOnly = it
                        selectedPhotos.clear()
                        dateGroupSelection.clear()
                    }
                )
            }

            // 照片网格
            LazyVerticalGrid(
                state = gridState,
                columns = GridCells.Fixed(4),
                modifier = Modifier
                    .fillMaxSize(),
                horizontalArrangement = Arrangement.spacedBy(4.dp),
                verticalArrangement = Arrangement.spacedBy(4.dp),
                contentPadding = PaddingValues(8.dp)
            ) {
                photosByDate.forEach { (date, photos) ->
                    // 日期标题
                    item(span = { GridItemSpan(4) }) {
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(8.dp, 4.dp),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(
                                text = date,
                                fontSize = 14.sp,
                                color = Color.Gray
                            )

                            // 日期组选择按钮
                            Box(
                                modifier = Modifier
                                    .size(20.dp)
                                    .clip(CircleShape)
                                    .background(
                                        if (dateGroupSelection[date] == true)
                                            Color.Red
                                        else
                                            Color.White.copy(alpha = 0.7f)
                                    )
                                    .pointerInput(Unit) {
                                        detectTapGestures(
                                            onTap = { toggleDateGroupSelection(date) }
                                        )
                                    },
                                contentAlignment = Alignment.Center
                            ) {
                                if (dateGroupSelection[date] == true) {
                                    Icon(
                                        imageVector = Icons.Default.Check,
                                        contentDescription = "已选中该组",
                                        tint = Color.White,
                                        modifier = Modifier.size(14.dp)
                                    )
                                }
                            }
                        }
                    }

                    // 照片项
                    items(photos) { photo ->
                        val painter = painterResource(id = photo.imageResId)
                        val isSelected = selectedPhotos.contains(photo.id)
                        Box(
                            modifier = Modifier
                                .aspectRatio(1f)
                                .clip(RoundedCornerShape(4.dp))
                                .background(Color.LightGray)
                                .pointerInput(Unit) {
                                    detectTapGestures(
                                        onTap = {
                                            if (isSelected) {
                                                selectedPhotos.remove(photo.id)
                                                val groupStillSelected =
                                                    photos.any { selectedPhotos.contains(it.id) }
                                                if (!groupStillSelected) {
                                                    dateGroupSelection[date] = false
                                                }
                                            } else {
                                                selectedPhotos.add(photo.id)
                                                val allGroupSelected =
                                                    photos.all { selectedPhotos.contains(it.id) }
                                                if (allGroupSelected) {
                                                    dateGroupSelection[date] = true
                                                }
                                            }
                                        }
                                    )
                                }
                        ) {
                            Image(
                                painter = painter,
                                contentDescription = null,
                                contentScale = ContentScale.Crop,
                                modifier = Modifier.fillMaxSize()
                            )

                            // 未备份标识
                            if (!photo.isBackedUp) {
                                Box(
                                    modifier = Modifier
                                        .align(Alignment.BottomStart)
                                        .padding(4.dp)
                                        .size(16.dp)
                                        .clip(CircleShape)
                                        .background(Color.Red)
                                )
                            }

                            // 选中状态指示器
                            Box(
                                modifier = Modifier
                                    .align(Alignment.TopEnd)
                                    .padding(4.dp)
                            ) {
                                Box(
                                    modifier = Modifier
                                        .size(20.dp)
                                        .clip(CircleShape)
                                        .background(
                                            if (isSelected) Color.Red else Color.White.copy(
                                                alpha = 0.7f
                                            )
                                        ),
                                    contentAlignment = Alignment.Center
                                ) {
                                    if (isSelected) {
                                        Icon(
                                            imageVector = Icons.Default.Check,
                                            contentDescription = "已选中",
                                            tint = Color.White,
                                            modifier = Modifier.size(14.dp)
                                        )
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

@Preview(showBackground = true)
@Composable
fun AiPhotoScreenPreview() {
    AppTheme {
        AiPhotoAlbumScreen(
        )
    }
}